package cn.xmall.validators;

import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

public abstract class ExValidationUtils extends ValidationUtils {

    static public void notNull(Errors errors,Object object,String message) throws ExValidationException {
        notNull(errors,object,null,message);
    }

    static public void notNull(Errors errors,Object object,String errCode, String message) throws ExValidationException {
        Assert.notNull(errors, "Errors object must not be null");
        if (object == null) {
            errors.reject(errCode,message);
            throw new ExValidationException(message);
        }
    }

    static public void hasLength(Errors errors,String text, String message) throws ExValidationException {
        hasLength(errors,text,null,message);
    }
    static public void hasLength(Errors errors,String text, String errCode, String message) throws ExValidationException {
        Assert.notNull(errors, "Errors object must not be null");
        if (!StringUtils.hasLength(text)) {
            errors.reject(errCode,message);
            throw new ExValidationException(message);
        }
    }

    public static void hasText(Errors errors,String text,String message) throws ExValidationException {
        hasText(errors,text,null,message);
    }

    public static void hasText(Errors errors,String text, String errCode,String message) throws ExValidationException {
        Assert.notNull(errors, "Errors object must not be null");
        if (!StringUtils.hasText(text)) {
            errors.reject(errCode,message);
            throw new ExValidationException(message);
        }
    }

    public static void state(Errors errors, boolean expression,String message) throws ExValidationException {
        state(errors,expression,null,message);
    }

    public static void state(Errors errors, boolean expression, String errCode, String message) throws ExValidationException {
        Assert.notNull(errors, "Errors object must not be null");
        if (!expression) {
            errors.reject(errCode,message);
            throw new ExValidationException(message);
        }
    }

    public static void notEmpty(Errors errors,Object[] array,String message) throws ExValidationException {
        notEmpty(errors,array,null,message);
    }

    public static void notEmpty(Errors errors,Object[] array, String errCode,String message) throws ExValidationException {
        Assert.notNull(errors, "Errors object must not be null");
        if (ObjectUtils.isEmpty(array)) {
            errors.reject(errCode,message);
            throw new ExValidationException(message);
        }
    }
}
